/*
 * Copyright (C) 2016 Olmo Gallegos Hernández.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package es.voghdev.pdfviewpager;

import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.xw.repo.BubbleSeekBar;

import java.io.File;

import es.voghdev.pdfviewpager.library.PDFViewPager;
import es.voghdev.pdfviewpager.library.adapter.BasePDFPagerAdapter;
import es.voghdev.pdfviewpager.library.adapter.PDFPagerAdapter;
import es.voghdev.pdfviewpager.library.asset.CopyAsset;
import es.voghdev.pdfviewpager.library.asset.CopyAssetThreadImpl;

import static android.Manifest.permission.READ_EXTERNAL_STORAGE;

public class AssetOnSDActivity extends BaseSampleActivity {


    private final static int REQUEST_CODE = 42;
    public static final int PERMISSION_CODE = 42042;
    private static final int MSGTYPE_CHANGE_PAGER = 0;
    private static final int MSGTYPE_CHANGE_SEEKBAR = 1;


    final String[] sampleAssets = {"adobe.pdf", "sample.pdf"};

    PDFViewPager pdfViewPager;
    File pdfFolder;
    FrameLayout fl_layout;
    TextView tv_page_percent;//总页数
    BubbleSeekBar bubbleSeekBar;//进度条
    int currentProgress = 0;
    private Handler myHandler;
    private RelativeLayout bottomLayoutControler;


    public class MyHandler extends Handler {

        @Override
        public void handleMessage(Message msg) {
            if (msg.what == MSGTYPE_CHANGE_PAGER) {
                if (pdfViewPager != null) {
                    pdfViewPager.setCurrentItem(currentProgress);
                }
            } else if (msg.what == MSGTYPE_CHANGE_SEEKBAR) {
                if (bubbleSeekBar != null) {
                    bubbleSeekBar.setProgress(currentProgress);
                }
            }
            tv_page_percent.setText(String.valueOf(currentProgress) + "/" + String.valueOf(pdfViewPager.getAdapter().getCount()));
        }
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle(R.string.asset_on_sd);
        setContentView(R.layout.activity_asset_on_sd);

        fl_layout = (FrameLayout) findViewById(R.id.fl_layout);

        myHandler = new MyHandler();

        //加载本地pdf
        View tabBarView = getLayoutInflater().inflate(R.layout.activity_tab_bar, null);
        getSupportActionBar().setDisplayShowCustomEnabled(true);
        LinearLayout.LayoutParams layout = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        getSupportActionBar().setCustomView(tabBarView);
        Button loadFile = (Button) tabBarView.findViewById(R.id.btn_load_file);
        TextView titleText = (TextView) tabBarView.findViewById(R.id.tv_title);
        titleText.setText(getResources().getText(R.string.asset_on_sd));
        loadFile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pickFile();//选在文件
            }
        });

        pdfFolder = Environment.getExternalStorageDirectory();
        copyAssetsOnSDCard();
    }


    void pickFile() {
        int permissionCheck = ContextCompat.checkSelfPermission(this, READ_EXTERNAL_STORAGE);
        if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{READ_EXTERNAL_STORAGE},
                    PERMISSION_CODE
            );
            return;
        }
        launchPicker();
    }

    void launchPicker() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("application/pdf");
        try {
            startActivityForResult(intent, REQUEST_CODE);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(this, "加载文件出错.", Toast.LENGTH_SHORT).show();
        }
    }

    protected void copyAssetsOnSDCard() {
        final Context context = this;
        CopyAsset copyAsset = new CopyAssetThreadImpl(getApplicationContext(), new Handler(), new CopyAsset.Listener() {
            @Override
            public void success(String assetName, String destinationPath) {
                pdfViewPager = new PDFViewPager(context, getPdfPathOnSDCard());
                pdfViewPager.setPageMargin(20);
                pdfViewPager.setBackgroundColor(Color.GRAY);
                pdfViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
                    @Override
                    public void onPageSelected(int position) {
                        currentProgress = position;
                        myHandler.sendEmptyMessage(MSGTYPE_CHANGE_SEEKBAR);
                    }
                });

                FrameLayout.LayoutParams pagerParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
                fl_layout.addView(pdfViewPager, pagerParams);
                addBottomLayout();
            }

            @Override
            public void failure(Exception e) {
                e.printStackTrace();
                Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG).show();
            }
        });

        for (String asset : sampleAssets) {
            copyAsset.copy(asset, new File(pdfFolder, asset).getAbsolutePath());
        }
    }

    private void addBottomLayout() {
        FrameLayout.LayoutParams relativeLayoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, 150);
        bottomLayoutControler = new RelativeLayout(this);
        relativeLayoutParams.gravity = Gravity.BOTTOM;
        bottomLayoutControler.setBackgroundColor(Color.parseColor("#B3FDF5E6"));
        RelativeLayout.LayoutParams percentParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.MATCH_PARENT);
        tv_page_percent = new TextView(this);
        percentParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        percentParams.addRule(RelativeLayout.CENTER_VERTICAL);
        percentParams.setMargins(0, 0, 30, 0);
        tv_page_percent.setId(R.id.tv_percent_count);
        tv_page_percent.setTextColor(Color.BLUE);
        tv_page_percent.setBackgroundColor(Color.GREEN);
        tv_page_percent.setText(String.valueOf(currentProgress) + "/" + String.valueOf(pdfViewPager.getAdapter().getCount()));
        tv_page_percent.setGravity(Gravity.CENTER_VERTICAL);
        tv_page_percent.setTextSize(20);
        bottomLayoutControler.setVisibility(View.GONE);//隐藏底部导航
        bottomLayoutControler.addView(tv_page_percent, percentParams);
        fl_layout.addView(bottomLayoutControler, relativeLayoutParams);


        RelativeLayout.LayoutParams seekbarParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.MATCH_PARENT);
        seekbarParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        seekbarParams.addRule(RelativeLayout.CENTER_VERTICAL);
        seekbarParams.addRule(RelativeLayout.LEFT_OF, R.id.tv_percent_count);
        seekbarParams.setMargins(10, 0, 10, 0);
        bubbleSeekBar = new BubbleSeekBar(this);
        bubbleSeekBar.getConfigBuilder()
                .min(0)
                .max(((BasePDFPagerAdapter) pdfViewPager.getAdapter()).getCount())
                .trackColor(ContextCompat.getColor(this, R.color.color_gray))
                .secondTrackColor(ContextCompat.getColor(this, R.color.color_blue))
                .thumbColor(ContextCompat.getColor(this, R.color.color_blue))
                .bubbleColor(ContextCompat.getColor(this, R.color.color_green))
                .bubbleTextSize(18)
                .build();
        bubbleSeekBar.setOnProgressChangedListener(new BubbleSeekBar.OnProgressChangedListenerAdapter() {
            @Override
            public void onProgressChanged(BubbleSeekBar bubbleSeekBar, int progress, float progressFloat) {
                if (currentProgress != progress) {
                    currentProgress = progress;
                    myHandler.sendEmptyMessage(MSGTYPE_CHANGE_PAGER);
                }
            }
        });
        bottomLayoutControler.addView(bubbleSeekBar, seekbarParams);

        ((PDFPagerAdapter) pdfViewPager.getAdapter()).setPageClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (bottomLayoutControler.getVisibility() == View.VISIBLE) {
                    bottomLayoutControler.setVisibility(View.GONE);
                } else {
                    bottomLayoutControler.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    protected String getPdfPathOnSDCard() {
        File f = new File(pdfFolder, "adobe.pdf");
        return f.getAbsolutePath();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
            Uri uri = data.getData();
//            displayFromUri(uri);
            pdfViewPager = new PDFViewPager(this, getRealFilePath(this, uri));
            pdfViewPager.setPageMargin(20);
            pdfViewPager.setBackgroundColor(Color.GRAY);
            pdfViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
                @Override
                public void onPageSelected(int position) {
                    currentProgress = position;
                    myHandler.sendEmptyMessage(MSGTYPE_CHANGE_SEEKBAR);
                }
            });
//            setContentView(pdfViewPager);
            FrameLayout.LayoutParams pagerParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
            fl_layout.addView(pdfViewPager, pagerParams);
            addBottomLayout();
        }
    }


    public static String getRealFilePath(final Context context, final Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[],
                                           @NonNull int[] grantResults) {
        if (requestCode == PERMISSION_CODE) {
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                launchPicker();
            }
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (pdfViewPager != null) {
            ((BasePDFPagerAdapter) pdfViewPager.getAdapter()).close();
        }
    }

    public static void open(Context context) {
        Intent i = new Intent(context, AssetOnSDActivity.class);
        context.startActivity(i);
    }
}